<template>
  <div class="tableListBox">
    <div class="common-header">
      <div style="cursor: pointer" @click="back">
        <i class="vxe-icon-arrow-left" style="vertical-align: middle"></i
        ><span style="vertical-align: middle">返回</span>
      </div>
    </div>
    <div class="anthorContent">
      <el-scrollbar style="height: 100%">
        <p class="title"><span class="titleName">基础信息</span></p>
        <vxe-form :data="form" title-align="right" class-name="outForm" @submit="searchEvent">
          <vxe-form-item title="项目编号" field="code" :item-render="{}">
            <template #default="{ data }">
              <vxe-input
                v-model="data.projectCode"
                class="normal"
                placeholder="项目编号"
                disabled
                clearable
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="项目全称" field="projectName" :item-render="{}">
            <template #default="{ data }">
              <vxe-input v-model="data.projectName" class="normal" placeholder="项目全称" disabled></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="所属组织" field="belongOrganization" :item-render="{}">
            <template #default="{ data }">
              <vxe-input v-model="data.belongOrganization" class="normal" placeholder="所属组织" disabled></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="商务人员总数" field="businessPersonnelAmount" :item-render="{}">
            <template #default="{ data }">
              <vxe-input
                v-model="data.businessPersonnelAmount"
                class="normal"
                placeholder="商务人员总数"
                disabled
              ></vxe-input>
            </template>
          </vxe-form-item>
        </vxe-form>
        <p class="title">
          <span class="titleName">商务人员</span>
        </p>
        <div class="title-operation">
          <!-- <el-button type="primary" size="small" @click="insertEvent(-1)">增加检测参数</el-button> -->
          <el-button type="primary" size="small" @click="intoInside">调入内部员工</el-button>
          <el-button type="primary" size="small" @click="intoOutside">调入外部员工</el-button>
          <el-button type="primary" size="small" @click="addOutside">新增外部员工</el-button>
          <el-button type="primary" size="small" @click="manage">管理</el-button>
        </div>
        <CommonTable
          ref="common"
          :tableData="tableData"
          :columns="tableColumn"
          @pager="pager"
          @reload="getList"
          @outerStaff="outerStaff"
        />
      </el-scrollbar>
    </div>
    <User
      ref="user"
      :userList="internalUsers"
      :userListTotal="interUserTotal"
      type="checkbox"
      :config="{ key: 'psnname', id: 'psncode', name: '用户', tip: '姓名（编码）' }"
      @moreRole="moreRole"
      @search="searchInternalEmployee"
      @getPlanLedger="importInternalEmployee"
      @closePersonnel="close"
      @refreshPerson="searchInternalEmployee"
    />
    <SelectUser
      ref="loadOutUser"
      :tableData="users"
      :total="userTotal"
      :columns="userColumn"
      @pager="userPager"
      @search="searchExternalEmployee"
      @closePersonnel="close"
      @submit="importExternalEmployee"
    />
    <AddUser ref="addOutUser" :postList="postList" @addOutsideFn="addOutsideFn" />
    <AddUser ref="editOutUser" isEdit :postList="postList" @addOutsideFn="addOutsideFn" />
  </div>
</template>
<script>
import CommonTable from './common.vue';
import User from '/@/components/User';
import SelectUser from './components/SelectFromTableDialog';
import AddUser from './components/AddFormDialog';
import VXETable from 'vxe-table';
const enumeration = {
  EXTERNAL: '外部员工', // 外部员工
  INTERNAL: '内部员工', // 内部员工
};
export default {
  components: { CommonTable, User, SelectUser, AddUser },
  data() {
    return {
      form: {
        projectCode: '',
        projectName: '',
        belongOrganization: '',
        businessPersonnelAmount: '',
      },
      dataParams: {
        page: 1,
        size: 10,
      },
      importType: enumeration.INTERNAL,
      // employeeParams: {
      //   employeeName: '',
      //   idCard: '',
      //   page: 1,
      //   size: 10,
      // },
      tableColumn: [
        {
          field: 'employeeName',
          title: '姓名',
          editRender: {},
        },
        {
          field: 'category',
          title: '所属类别',
          editRender: {},
        },
        {
          field: 'employeeCode',
          title: '员工编码',
          editRender: {},
        },
        {
          field: 'idCard',
          title: '身份证',
          editRender: {},
        },
        {
          field: 'projectPost',
          title: '项目岗位',
          editRender: {},
        },
        {
          field: 'arrivalTime',
          title: '到岗时间',
          editRender: {
            default: 'd_arrivalTime',
          },
        },
        {
          field: 'leaveTime',
          title: '离岗时间',
          editRender: {},
        },
        {
          field: 'isPartTime',
          title: '是否兼职',
          editRender: {},
          slots: {
            default: 'd_isPartTime',
          },
        },
        {
          field: 'isPractice',
          title: '是否实习',
          editRender: {},
          slots: {
            default: 'd_isPractice',
          },
        },
        {
          title: '操作',
          align: 'center',
          headerAlign: 'left',
          slots: { default: 'operation' },
        },
      ],
      tableData: {},
      userColumn: [
        {
          type: 'checkbox',
          title: '',
          width: 60,
          editRender: {},
        },
        {
          field: 'employeeName',
          title: '姓名',
          editRender: {},
          width: 280,
          slots: {
            edit: 'employeeName',
          },
        },
        {
          field: 'idCard',
          title: '身份证',
          editRender: {},
          slots: {
            edit: 'idCard',
          },
        },
      ],
      users: [],
      internalUsers: [],
      userTotal: 0,
      interUserTotal: 0,
      postList: [],
    };
  },
  created() {
    this.getQuery();
    this.getList();
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      if (!query) {
        query = window.location.hash.split('?')[1];
      }
      if (!query) {
        return;
      }
      var vars = query.split('&');
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (pair[0] == variable) {
          return decodeURIComponent(pair[1]);
        }
      }
      return '';
    },
    getQuery() {
      const { projectCode, projectName, belongOrganization, businessPersonnelAmount } = this.$route.query;
      this.form.projectCode = projectCode;
      this.form.projectName = projectName;
      this.form.belongOrganization = belongOrganization;
      this.form.businessPersonnelAmount = businessPersonnelAmount;
    },
    async getPostList() {
      await this.$api.getPostList({ postType: 3, page: 1, size: 1000 }).then((res) => {
        const { list } = res.data;
        this.postList = list;
      });
    },
    async getList() {
      await this.$api
        .fetchEmployeeList({
          projectCode: this.form.projectCode,
          ...this.dataParams,
        })
        .then((res) => {
          try {
            const { projectEmployeeInventory } = res.data;
            if (projectEmployeeInventory) {
              projectEmployeeInventory?.list?.forEach((item) => {
                item.belongOrganization = this.form.belongOrganization;
                item.projectName = this.form.projectName;
              });
              this.tableData = projectEmployeeInventory;
              console.log(this.tableData);
            }
          } catch {}
        });
    },

    // 关闭弹窗时重置数据
    close() {
      this.internalUsers = [];
      this.users = [];
    },
    pager({ currentPage, pageSize }) {
      this.dataParams.page = currentPage;
      this.dataParams.size = pageSize;
      this.getList();
    },
    outerStaff(row) {
      this.$refs.editOutUser.form = row;
      this.$refs.editOutUser.dialogVisible = true;
    },
    // 选择内部员工弹窗事件
    getInnerEmployee(employeeParams = { page: 1, size: 10 }) {
      return this.$api.fetchInnerrStaffList({ ...employeeParams }).then((res) => res.data);
    },
    async intoInside() {
      this.importType = enumeration.INTERNAL;
      this.interUserTotal = 0;
      this.getInternalEmployee();
      this.$refs.user.dialogVisible = true;
    },
    moreRole(employeeParams) {
      const { code: psncode, name: psnname, ...rest } = employeeParams;
      this.getInternalEmployee({ psncode, psnname, ...rest });
    },
    searchInternalEmployee(employeeParams) {
      const { code: psncode, name: psnname, ...rest } = employeeParams;
      this.internalUsers = [];
      this.getInternalEmployee({ psncode, psnname, ...rest });
    },
    async getInternalEmployee(employeeParams = { page: 1, size: 10 }) {
      const data = await this.getInnerEmployee(employeeParams);
      this.internalUsers = [...this.internalUsers, ...data?.list];
      this.interUserTotal = data.total;
    },
    // 选择外部员工弹窗事件
    getOurterEmployee(employeeParams = { page: 1, size: 10 }) {
      return this.$api.fetchOuterStaffList({ ...employeeParams, importType: this.importType }).then((res) => res.data);
    },
    async intoOutside() {
      this.importType = enumeration.EXTERNAL;
      this.userTotal = 0;
      this.getExternalEmployee();
      this.$refs.loadOutUser.dialogVisible = true;
    },
    userPager(employeeParams) {
      this.getExternalEmployee(employeeParams);
    },
    searchExternalEmployee(employeeParams) {
      this.internalUsers = [];
      this.getExternalEmployee(employeeParams);
    },
    async getExternalEmployee(employeeParams) {
      const data = await this.getOurterEmployee(employeeParams);
      this.users = data?.list;
      this.userTotal = data.total;
    },

    importInternalEmployee(list) {
      const { projectCode, projectName, belongOrganization } = this.form;
      const users = list.map((item) => {
        return {
          importType: this.importType,
          projectCode,
          belongProject: projectName,
          belongOrganization,
          idCard: item.certid,
          employeeCode: item.psncode,
          employeeName: item.psnname,
        };
      });
      this.$api.importEmployee(users).then((res) => {
        VXETable.modal.message({
          content: '调入成功',
          status: 'success',
        });
        this.$refs.user.dialogVisible = false;
        this.getList();
      });
    },
    importExternalEmployee(list) {
      const { projectCode, projectName, belongOrganization } = this.form;
      const users = list.map((item) => {
        return {
          importType: this.importType,
          projectCode,
          belongProject: projectName,
          belongOrganization,
          idCard: item.idCard,
          employeeCode: item.employeeCode,
          employeeName: item.employeeName,
        };
      });
      this.$api.importEmployee(users).then((res) => {
        VXETable.modal.message({
          content: '调入成功',
          status: 'success',
        });
        this.$refs.loadOutUser.dialogVisible = false;
        this.getList();
      });
    },
    async addOutside() {
      this.getPostList();
      this.$refs.addOutUser.dialogVisible = true;
    },
    addOutsideFn(data, type) {
      const { projectCode, projectName, belongOrganization } = this.form;
      this.$api.addExternalEmployee([{ projectCode, projectName, belongOrganization, ...data }]).then((res) => {
        if (res.code === 0) {
          VXETable.modal.message({
            content: type === 'add' ? '新增成功' : '已成功调出',
            status: 'success',
          });
          this.$refs.addOutUser.dialogVisible = false;
          this.$refs.editOutUser.dialogVisible = false;
          this.getList();
          setTimeout(() => {
            this.$refs.addOutUser.reset();
          }, 500);
        }
      });
    },
    manage() {
      this.$router.push({ path: '/staffList/manage', query: { ...this.form } });
    },
    async insertEvent(row) {
      const $table = this.$refs.common.$refs.table;
      const record = {
        params: '',
        pricingUnit: '',
        unit: '',
        area: '',
        hours: '',
        remark: '',
      };
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setActiveCell(newRow);
    },
    save() {},
    edit() {},
    searchEvent() {},
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .vxe-form.outForm {
    .vxe-form--item-content {
      width: 280px;
    }
    .vxe-row .vxe-form--item {
      width: 25%;
    }
  }
}
</style>
